package org.security.exception;

import com.alibaba.fastjson.JSONObject;
import org.security.enums.CustomExceptionType;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static org.security.enums.CustomExceptionType.USERORPASS_ERROR;

/**
 * @author jt
 * @date 2024/7/21 0:26
 */
public class CustomException{
    //异常错误编码
    private int code;
    //异常信息
    private String message;

    //无参构造函数
    public CustomException() {
    }

    //使用分类固化异常，不希望程序员创建异常 ，===使用CustomExceptionType 来限定范围
    public CustomException(CustomExceptionType exceptionTypeEnum) {
        this.code = exceptionTypeEnum.getCode();
        this.message = exceptionTypeEnum.getDesc();
    }
    //这个message信息是要最后返回给前端的，所以需要用友好的提示来表达异常发生的原因或内容
    public CustomException(CustomExceptionType exceptionTypeEnum,
                           String message) {
        this.code = exceptionTypeEnum.getCode();
        this.message = message;
    }

    public int getCode() {
        return code;
    }


    public String getMessage() {
        return message;
    }

    public static HttpServletResponse errorToResponse(HttpServletResponse response,HttpStatus status,
                                                      CustomExceptionType customExceptionType){
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(status.value());
        CustomException customException = new CustomException(customExceptionType);
        try{
            httpServletResponse.getWriter().write(JSONObject.toJSONString(customException));
            throw new RuntimeException(customExceptionType.getDesc());
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return httpServletResponse;
    }

}
